<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1100px"
      destroy-on-close
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="112px"
        :inline="true"
      >
        <!-- 只读状态显示遮罩 -->
        <!-- <div v-if="props.isReadonly" class="formCover"></div> -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="工艺路线编号" prop="routingCode">
              <el-input
                v-show="!props.isReadonly"
                v-model="formData.routingCode"
                placeholder="请输入工艺路线编号"
              />
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{ formData.routingCode }}</span
              >
            </el-form-item>
          </el-col>
          <el-col :span="8"
            ><el-form-item label="工艺路线名称" prop="routingName">
              <el-input
                v-show="!props.isReadonly"
                v-model="formData.routingName"
                placeholder="请输入工艺路线名称"
              />
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{ formData.routingName || "" }}</span
              >
            </el-form-item></el-col
          >
          <el-col :span="8"
            ><el-form-item label="版本编号" prop="versionNo">
              <el-input
                v-show="!props.isReadonly"
                v-model="formData.versionNo"
                placeholder="请输入版本编号"
              />
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{ formData.versionNo || "" }}</span
              >
            </el-form-item></el-col
          >
        </el-row>

        <el-row>
          <el-col :span="8"
            ><el-form-item label="工厂" prop="plantId">
              <el-select
                v-show="!props.isReadonly"
                v-model="formData.plantId"
                placeholder="请选择工厂"
                clearable
                @change="selectPlant"
                filterable
              >
                <el-option
                  v-for="item in plantList"
                  :key="item.id"
                  :label="item.organizationCode"
                  :value="item.id"
                />
              </el-select>
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{ formData.plantCode || " " }}</span
              >
            </el-form-item></el-col
          >
          <el-col :span="8"
            ><el-form-item label="工作中心">
              <el-select
                v-show="!props.isReadonly"
                v-model="formData.workCenterId"
                placeholder="请选择工作中心"
                clearable
                filterable
              >
                <el-option
                  v-for="item in workShopList"
                  :key="item.id"
                  :label="`${item.workshopCode}-${item.workshopName}`"
                  :value="item.id"
                />
              </el-select>
              <span
                class="w-[192px] border_b_black text-[13px]"
                v-show="props.isReadonly"
                >{{
                  formData.workCenterCode
                    ? `${formData.workCenterCode}-${formData.workCenterName}`
                    : ""
                }}</span
              >
            </el-form-item></el-col
          >
          <el-col :span="8"
            ><el-form-item label="工艺路线分组" prop="routingGroupId">
              <el-select
                v-show="!props.isReadonly"
                v-model="formData.routingGroupId"
                clearable
                placeholder="请选择工艺路线分组"
                filterable
              >
                <el-option
                  v-for="item in routeGroups"
                  :key="item.id"
                  :label="item.routingGroupName"
                  :value="item.id"
                />
              </el-select>
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{ formData.routingGroupName }}</span
              >
            </el-form-item></el-col
          >
        </el-row>

        <el-row>
          <el-col :span="8"
            ><el-form-item label="生产节拍" prop="tactTime">
              <el-input
                v-show="!props.isReadonly"
                v-model="formData.tactTime"
                style="max-width: 192px"
                placeholder="请输入"
              >
                <template #append>秒</template>
              </el-input>
              <span class="w-[192px] border_b_black" v-show="props.isReadonly"
                >{{ formData.tactTime }}秒</span
              >
            </el-form-item></el-col
          >
          <el-col :span="8"
            ><el-form-item label="整体加功时长" prop="totalTime">
              <el-input
                v-show="!props.isReadonly"
                v-model="formData.totalTime"
                style="max-width: 192px"
                placeholder="请输入"
              >
                <template #append>秒</template>
              </el-input>
              <span class="w-[192px] border_b_black" v-show="props.isReadonly"
                >{{ formData.totalTime }}秒</span
              >
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="制造环节角色" prop="manufacturingRole">
              <el-select
                v-show="!props.isReadonly"
                v-model="formData.manufacturingRole"
                placeholder="请选择制造环节角色"
                clearable
              >
                <el-option
                  v-for="item in useDictionary('ManufacturingRole')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{
                  useDictionary("ManufacturingRole", formData.manufacturingRole)
                }}</span
              >
            </el-form-item></el-col
          >
        </el-row>

        <el-row>
          <el-col :span="8"
            ><el-form-item label="需要人数" prop="memberUse">
              <el-input
                v-show="!props.isReadonly"
                v-model="formData.memberUse"
                placeholder="请输入需要人数"
              />
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{ formData.memberUse }}</span
              >
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="路线状态" prop="routingState">
              <el-select
                v-show="!props.isReadonly"
                v-model="formData.routingState"
                placeholder="请选择路线状态"
                clearable
              >
                <el-option
                  v-for="item in useDictionary('RoutingState')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{
                  useDictionary("RoutingState", formData.routingState)
                }}</span
              >
            </el-form-item></el-col
          >
          <el-col :span="8"
            ><el-form-item label="是否启用" prop="enabled">
              <el-radio-group
                v-show="!props.isReadonly"
                v-model="formData.enabled"
              >
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
              <span
                class="w-[192px] border_b_black"
                v-show="props.isReadonly"
                >{{ useDictionary("Enabled", formData.enabled ?? "") }}</span
              >
            </el-form-item></el-col
          >
        </el-row>

        <div style="width: 100%">
          <el-form-item label="备注" prop="remarks" style="width: 96%">
            <el-input
              v-model="formData.remarks"
              placeholder="请输入备注"
              type="textarea"
              show-word-limit
              :maxlength="255"
              :autosize="{ minRows: 3, maxRows: 4 }"
              v-show="!props.isReadonly"
            />
            <span v-show="props.isReadonly" class="border_b_black">{{
              formData.remarks
            }}</span>
          </el-form-item>
        </div>
      </el-form>

      <template v-if="!props.isReadonly" #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="loading" @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import {
  getPlantList,
  getWorkShopList,
  getMesRouteGroupList,
} from "@/utils/commonData";
import { validateZeroNumber } from "@/utils/commonHooks";

defineOptions({
  name: "AddMesRouting",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  plantList: {
    type: Array,
    default: () => [],
  },
  routeGroups: {
    type: Array,
    default: () => [],
  },
});

const { plantList, routeGroups } = toRefs(props);

// 工作中心列表
const workShopList: any = ref([]);

async function selectPlant(id: string) {
  if (id) {
    const currentObj: any = plantList.value.filter((e: any) => e.id === id);
    console.log("currentObj", currentObj);
    formData.plantCode = currentObj[0]?.organizationCode || "";
  } else {
    formData.plantCode = "";
  }
  workShopList.value = (await getWorkShopList(id)) ?? [];
  formData.workCenterId = "";
}

/** 弹窗显示隐藏 */
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

// 小数校验
function validator1(rule, value, callback: (a?: any) => {}) {
  if (!value) {
    //先判断空可以过
    // callback(new Error("请输入2位整数3位小数"));
    return true;
  } else {
    if (/^\d{1,8}(\.\d{0,9})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入小数"));
    }
  }
}
/** 定义form信息 */
const rules = reactive({
  routingCode: [
    { required: true, message: "请输入工艺路线编号", trigger: "blur" },
    { max: 50, message: "不能超过50个字符", trigger: "blur" },
  ],
  routingName: [
    { required: true, message: "请输入工艺路线名称", trigger: "blur" },
    { max: 50, message: "不能超过50个字符", trigger: "blur" },
  ],
  versionNo: [
    { required: true, message: "请输入版本编号", trigger: "blur" },
    { max: 50, message: "不能超过50个字符", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  routingGroupId: [{ message: "请选择工艺路线分组", trigger: "change" }],
  tactTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
    { required: true, message: "请输入生产节拍", trigger: "blur" },
    { pattern: /^[1-9]\d*$/, message: "请输入大于0的整数", trigger: "blur" },
  ],
  totalTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  memberUse: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  manufacturingRole: [
    { required: true, message: "请选择制造环节角色", trigger: "change" },
  ],
  routingState: [
    { required: true, message: "请选择路线状态", trigger: "change" },
  ],
  remarks: [
    { message: "请输入备注", trigger: "blur" },
    { max: 255, message: "不能超过255个字符", trigger: "blur" },
  ],
  enabled: [{ required: true, message: "请选择是否启用", trigger: "change" }],
});

const formRef = ref(ElForm);

const initForm = {
  enabled: 1,
  remarks: "",
  id: "",
  routingCode: "",
  routingName: "",
  versionNo: "",
  plantCode: "",
  plantId: "",
  workCenterId: "",
  workCenterCode: "",
  workCenterName: "",
  routingGroupId: "",
  routingGroupName: "",
  tactTime: "",
  manufacturingRole: "",
  memberUse: "",
  routingState: "",
  totalTime: "",
};
let formData = reactive(JSON.parse(JSON.stringify(initForm)));

/** 编辑赋值 */
watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        routingCode,
        routingName,
        versionNo,
        plantCode,
        plantId,
        workCenterId,
        workCenterCode,
        workCenterName,
        routingGroupId,
        routingGroupName,
        tactTime,
        manufacturingRole,
        memberUse,
        routingState,
        totalTime,
        remarks,
        enabled,
      } = newVal;
      Object.assign(formData, {
        ...newVal,
        id,
        routingCode,
        routingName,
        versionNo,
        plantCode,
        plantId,
        workCenterId,
        workCenterCode,
        workCenterName,
        routingGroupId,
        routingGroupName,
        tactTime,
        manufacturingRole,
        memberUse,
        routingState,
        totalTime,
        remarks,
        enabled,
      });
      workShopList.value = (await getWorkShopList(formData.plantId)) ?? [];
      formData.manufacturingRole = formData.manufacturingRole.toString();
      formData.routingState = formData.routingState.toString();
    } else {
      workShopList.value = [];
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  selectPlant("");
  workShopList.value = [];
}

const loading = ref(false);

/** 角色保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesrouting/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`${text}成功`);
      emit("reset-table", formData.id || "");
      closeDialog();
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style lang="scss" scoped>
.el-form {
  position: relative;
  .formCover {
    position: absolute;
    top: 0;
    width: 100%;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 2000;
    cursor: default;
  }
  .border_b_black {
    border-bottom: 1px solid #e4e7ed;
    min-height: 33px;
    padding-left: 3px;
  }
}
</style>
